import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../../services/EventBus.dart';
import '../../services/ScreenAdapter.dart';
import '../../services/UserServices.dart';
import '../../widget/JdButton.dart';
import '../../widget/SlideAnination.dart';

class UserPage extends StatefulWidget {
  const UserPage({super.key});

  @override
  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  bool isLogin = false; // 是否登录
  List userInfo = []; // 用户信息

  @override
  void initState() {
    super.initState();
    _getUserinfo();

    // 监听登录页面改变的事件
    eventBus.on<UserEvent>().listen((event) {
      print(event.str);
      _getUserinfo();
    });
  }

  // 获取本地用户信息并设置为当前用户信息
  _getUserinfo() async {
    var isLogin = await UserServices.getUserLoginState();
    var userInfo = await UserServices.getUserInfo();
    print("isLogin: $isLogin");
    print("userInfo: $userInfo");

    setState(() {
      this.userInfo = userInfo;
      this.isLogin = isLogin;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Container(
            height: ScreenAdapter.height(180),
            width: double.infinity,
            margin: const EdgeInsets.fromLTRB(15, 20, 15, 5),
            decoration: BoxDecoration(
              // 渐变背景颜色
              gradient: LinearGradient(
                colors: [Colors.blue, Colors.blue.shade200],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              // 阴影效果
              boxShadow: [
                BoxShadow(
                  color: Colors.blue.withOpacity(0.5),
                  spreadRadius: 5,
                  blurRadius: 10,
                  offset: const Offset(0, 6),
                ),
              ],
              // 圆角边框
              borderRadius: const BorderRadius.all(Radius.circular(50)),
            ),
            child: Row(
              children: [
                Container(
                  margin: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                  // 用户头像
                  child: ClipOval(
                    child: Image.asset(
                      'assets/images/user.png',
                      fit: BoxFit.cover,
                      width: ScreenAdapter.width(100),
                      height: ScreenAdapter.width(100),
                    ),
                  ),
                ),
                // 判断用户是否登录
                !isLogin
                    ? Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            Get.toNamed("/login");
                          },
                          child: Text("login_or_register".tr,
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold)),
                        ),
                      )
                    : Expanded(
                        flex: 1,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 显示用户名
                            Text(
                              "${'username'.tr}: ${userInfo[0]["username"]}",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenAdapter.size(32),
                                  fontWeight: FontWeight.bold),
                            ),
                            // 显示用户等级
                            Text(
                              "普通会员".tr,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenAdapter.size(24)),
                            ),
                          ],
                        ),
                      )
              ],
            ),
          ), // 动画效果
          const SizedBox(height: 20),
          // 各个功能项，添加动画效果
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.assignment,
              color: Colors.red,
              title: "all_orders".tr,
              onTap: () => Get.toNamed("/order"),
            ),
          ),
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.payment,
              color: Colors.green,
              title: "pending_payment".tr,
            ),
          ),
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.receipt,
              color: Colors.orange,
              title: "pending_receipt".tr,
            ),
          ),
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.star,
              color: Colors.blue,
              title: "my_favorites".tr,
            ),
          ),
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.people,
              color: Colors.purple,
              title: "online_service".tr,
            ),
          ),
          SlideAnimation(
            child: _buildListTile(
              icon: Icons.settings,
              title: "settings".tr,
              onTap: () => Get.toNamed("/settings"),
            ),
          ),
          const SizedBox(height: 20),
          // 显示退出登录按钮
          isLogin
              ? Align(
                  alignment: Alignment.center, // 中心对齐
                  child: SizedBox(
                    width: 420, // 设置宽度
                    child: JdButton(
                      text: "Logout".tr,
                      cb: () {
                        UserServices.loginOut(); // 退出登录
                        _getUserinfo();
                      },
                    ).animate().fadeIn(duration: 500.ms), // 动画效果
                  ),
                )
              : const Text(""),
        ],
      ).animate().fadeIn(duration: 500.ms), // 动画效果
    );
  }

  // 构建列表项
  Widget _buildListTile(
      {required IconData icon,
      Color color = Colors.black54,
      required String title,
      Function()? onTap}) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 25, vertical: 15), // 外边距
      elevation: 5, // 阴影
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15), // 圆角边框
      ),
      child: ListTile(
        leading: Icon(icon, color: color, size: 28), // 图标
        title: Text(
          title,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        onTap: onTap,
      ),
    );
  }
}
